// pages/addcompany/addcompany.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    defaultSize: 'default',
    primarySize: 'default',
    warnSize: 'default',
    disabled: false,
    plain: false,
    loading: false,
    onPause: false,
    officeId: '',
    name: '',
    address: '',
    addressNow: '',
    phone: '',
    region: ['河北省', '保定市', '莲池区'],
    regionNow: ['河北省', '保定市', '莲池区'],
    seleCheckitems: [],
    imageArray: [],
    imagePathArray: [],
    date: '2020-01-19',
    situationItem: {
      name: '1',
      value: 'A.14天内，在湖北省居住过或进入过湖北省境内'
    },
    situationItem1: {
      name: '2',
      value: 'B.14天内，接触过来自湖北省的人员'
    },
    situationItem2: {
      name: '3',
      value: 'C.14天内，接触过本地发热病人'
    },
    situationItem3: {
      name: '4',
      value: 'D.14天内，本人是否出现过发热、乏力、干咳症状'
    },
    situationItem4: {
      name: '5',
      value: 'E.现在是否有一下症状1、发热(体温高于37.3度)2、乏力3、干咳4、其他'
    },
    situation: '否',
    situation1: '否',
    situation2: '否',
    situation3: '否',
    situation4: '否',
    emergencyContactArray: [{
      'name': '',
      'phone': ''
    }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //年  
    var Y = date.getFullYear();
    //月  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日  
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

    that.setData({
      officeId: options.officeId,
      date: Y + '-' + M + '-' + D,
    })
    console.log(that.data.officeId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    if (that.data.onPause == true) {

      var timestamp = Date.parse(new Date());
      var date = new Date(timestamp);
      //年  
      var Y = date.getFullYear();
      //月  
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      //日  
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

      that.setData({
        onPause: false,
        name: '',
        address: '',
        addressNow: '',
        phone: '',
        region: ['河北省', '保定市', '莲池区'],
        regionNow: ['河北省', '保定市', '莲池区'],
        seleCheckitems: [],
        imageArray: [],
        imagePathArray: [],
        date: Y + '-' + M + '-' + D,
        situationItem: {
          name: '1',
          value: 'A.14天内，在湖北省居住过或进入过湖北省境内'
        },
        situationItem1: {
          name: '2',
          value: 'B.14天内，接触过来自湖北省的人员'
        },
        situationItem2: {
          name: '3',
          value: 'C.14天内，接触过本地发热病人'
        },
        situationItem3: {
          name: '4',
          value: 'D.14天内，本人是否出现过发热、乏力、干咳症状'
        },
        situationItem4: {
          name: '5',
          value: 'E.现在是否有一下症状1、发热(体温高于37.3度)2、乏力3、干咳4、其他'
        },
        situation: '否',
        situation1: '否',
        situation2: '否',
        situation3: '否',
        situation4: '否',
        emergencyContactArray: [{
          'name': '',
          'phone': ''
        }],
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 添加紧急联系人
   */
  addEmergencyContact: function(e) {

    var that = this;
    if (that.data.emergencyContactArray.length >= 2) {
      wx.showToast({
        title: '最多添加2个紧急联系人',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    var mergencyContactS = that.data.emergencyContactArray;
    mergencyContactS.push({
      'name': '',
      'phone': ''
    });
    that.setData({
      emergencyContactArray: mergencyContactS
    })

  },

  /**
   * 紧急联系人名字
   */
  emergencyContactNameUpdateInputValue: function(e) {

    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.emergencyContactArray[index];
    model.name = e.detail.value;
    console.log(that.data.emergencyContactArray)
  },

  /**
   * 紧急联系人电话
   */
  emergencyContactPhoneUpdateInputValue: function(e) {

    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.emergencyContactArray[index];
    model.phone = e.detail.value;

  },

  /**
   * 添加图片
   */
  addImageBtnClick() {
    var that = this;
    if (that.data.imageArray.length >= 2) {

      wx.showToast({
        title: '最多选择2张图片',
        icon: 'none'
      })
      return;
    }

    var pics = that.data.imageArray;
    wx.chooseImage({
      count: 2 - that.data.imageArray.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          imageArray: pics.concat(tempFilePaths)
        })
        console.log(that.data.imageArray)
      }
    })
  },
  // 预览图集
  previewImage(e) {

    var that = this
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: that.data.imageArray[index],
      urls: that.data.imageArray

    });
  },
  //删除图片
  deleteImage(e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var imageArray = that.data.imageArray
    imageArray.splice(index, 1);
    that.setData({
      imageArray: imageArray
    })
  },

  /**
   * 返回时间
   */
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this
    that.setData({
      date: e.detail.value
    })
  },

  /**
   * 更新来源地
   */
  bindRegionChange: function(e) {
    var that = this
    that.setData({
      region: e.detail.value
    })
  },

  /**
   * 更新现居住地
   */
  bindRegionChangeNow: function(e) {
    var that = this
    that.setData({
      regionNow: e.detail.value
    })
  },

  /**
   * 姓名
   */
  inputName: function(e) {
    var that = this
    that.data.name = e.detail.value;
    console.log(that.data.name)
  },

  /**
   * 联系方式
   */
  inputPhone: function(e) {
    var that = this
    that.data.phone = e.detail.value;
  },

  /**
   * 详细地址
   */
  inputAddress: function(e) {
    var that = this
    that.data.address = e.detail.value
  },
  /**
   * 详细地址
   */
  inputAddressNow: function(e) {
    var that = this
    that.data.addressNow = e.detail.value
  },


  /**
   * 多选事件
   */
  checkboxChange: function() {
    var that = this;
    var value = that.data.situation
    if (value == '是') {
      that.setData({
        situation: '否'
      })
    } else {
      that.setData({
        situation: '是'
      })
    }
    console.log(that.data.situation)
  },
  /**
   * 多选事件
   */
  checkboxChange1: function() {
    var that = this;
    var value = that.data.situation1
    if (value == '是') {
      that.setData({
        situation1: '否'
      })
    } else {
      that.setData({
        situation1: '是'
      })
    }
    console.log(that.data.situation1)
  },
  /**
   * 多选事件
   */
  checkboxChange2: function() {
    var that = this;
    var value = that.data.situation2
    if (value == '是') {
      that.setData({
        situation2: '否'
      })
    } else {
      that.setData({
        situation2: '是'
      })
    }
    console.log(that.data.situation2)
  },
  /**
   * 多选事件
   */
  checkboxChange3: function() {
    var that = this;
    var value = that.data.situation3
    if (value == '是') {
      that.setData({
        situation3: '否'
      })
    } else {
      that.setData({
        situation3: '是'
      })
    }
    console.log(that.data.situation3)
  },
  /**
   * 多选事件
   */
  checkboxChange4: function() {
    var that = this;
    var value = that.data.situation4
    if (value == '是') {
      that.setData({
        situation4: '否'
      })
    } else {
      that.setData({
        situation4: '是'
      })
    }
    console.log(that.data.situation4)
  },

  /**
   * 提交
   */
  submit: function() {
    var that = this;
    if (that.data.name == '') {
      wx: wx.showToast({
        title: '请输入员工姓名',
        icon: 'none'
      })
      return
    }
    if (that.data.phone == '') {
      wx: wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      })
      return
    }
    if (that.data.address == '') {
      wx: wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return
    }
    if (that.data.addressNow == '') {
      wx: wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '确认',
      content: '是否要提交员工信息',
      success: function(res) {
        if (res.confirm) {

          var emergency = that.data.emergencyContactArray;
          var model = {};
          model.openid = getApp().globalData.openId;
          model.name = that.data.name;
          model.lyArea = that.data.region[0];
          model.lyArea1 = that.data.region[1];
          model.lyArea2 = that.data.region[2];
          model.lyArea3 = that.data.address;
          model.jzArea = that.data.regionNow[0];
          model.jzArea1 = that.data.regionNow[1];
          model.jzArea2 = that.data.regionNow[2];
          model.jzArea3 = that.data.addressNow;
          model.phone = that.data.phone;
          model.backDate = that.data.date;
          model.situation = that.data.situation;
          model.situation1 = that.data.situation1;
          model.situation2 = that.data.situation2;
          model.situation3 = that.data.situation3;
          model.situation4 = that.data.situation4;
          model.openid = getApp().globalData.openId;
          model.officeid = that.data.officeId;
          if (emergency.length == 1) {
            model.jjName = emergency[0].name;
            model.jjPhone = emergency[0].phone;
            model.jjName1 = '';
            model.jjPhone1 = '';
          } else if (emergency.length == 2) {
            model.jjName = emergency[0].name;
            model.jjPhone = emergency[0].phone;
            model.jjName1 = emergency[1].name;
            model.jjPhone1 = emergency[1].phone;
          } else {
            model.jjName = '';
            model.jjPhone = '';
            model.jjName1 = '';
            model.jjPhone1 = '';
          }

          wx.showLoading({
            title: '正在提交...',
          });

          //上传图片
          var imageArray = that.data.imageArray;
          if (imageArray.length > 0) {
            that.data.imagePathArray = [];
            for (var i = 0; i < imageArray.length; i++) {
              var imageSrc = imageArray[i];
              (function(index) {
                wx.uploadFile({
                  url: getApp().BASE_URL + '/wxoffice/uploadOfficeUserOne',
                  filePath: imageSrc,
                  name: 'image',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                  success(res) {
                    var responce = JSON.parse(res.data)
                    var img = responce.data;
                    console.log(img)
                    that.data.imagePathArray.push(img)

                    if (index == imageArray.length - 1) {
                      that.uploadModel(model)

                    }


                  },
                  fail() {
                    wx.showToast({
                      title: '上传错误，请重试',
                      icon: 'none'
                    })
                    that.setData({
                      imagePathArray: []
                    })
                  }
                })
              })(i)
            }
          } else {
            that.data.imagePathArray = [];
            that.uploadModel(model)
          }


        } else if (res.cancel) {
          console.log('用户点击了取消')
        }
      }
    })
  },

  /**
   * 上传数据
   */
  uploadModel: function(model) {
    var that = this;
    var file = '';

    for (var i = 0; i < that.data.imagePathArray.length; i++) {
      file += that.data.imagePathArray[i] + ',';
    }

    model.file = file;
    console.log(model)

    wx.request({
      url: getApp().BASE_URL + '/wxoffice/addOfficePeople',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: model,
      success: function(res) {
        console.log(res)
        if (res.data.code == 200) {
          wx.hideLoading();
          that.data.onPause = true;
          wx.navigateTo({
            url: '../staffsuccess/staffsuccess',
          })
          //   wx.showToast({
          //     title: '添加员工成功',
          //     icon: 'none'
          //   })
          //   setTimeout(function() {
          //     wx.navigateBack({
          //       delta: 1
          //     })
          //   }, 2000)

        }
      },
      fail: function(res) {
        wx.hideLoading();
        that.showErroMessage(res.data.msg)
      },
      complete: function(res) {

      }
    })

  },

  /**
   * 显示信息
   */
  showErroMessage: function(mes) {
    wx.showToast({
      title: mes,
      icon: 'none',
      duration: 1500
    })
  }


})